﻿CREATE TABLE [dbo].[ArticoleAliniate] (
    [ArtAl]              VARCHAR (40)  NOT NULL,
    [Denumire]           VARCHAR (200) NOT NULL,
    [AAParinte]          VARCHAR (40)  NOT NULL,
    [Terminal]           BIT           NOT NULL,
    [Titlu]              VARCHAR (100) NOT NULL,
    [Categorii]          VARCHAR (50)  NOT NULL,
    [TermDenumire]       VARCHAR (100) NOT NULL,
    [StartDenumire]      VARCHAR (100) NOT NULL,
    [Anexa6]             BIT           NOT NULL,
    [CodUnitate]         SMALLINT      CONSTRAINT [DF_ArticoleAliniate_CodUnitate] DEFAULT ((0)) NOT NULL,
    [ExecutieCheltuieli] BIT           CONSTRAINT [DF_ArticoleAliniate_ExecutieCheltuieli] DEFAULT ((0)) NOT NULL,
    CONSTRAINT [PK_ArticoleAliniate] PRIMARY KEY CLUSTERED ([ArtAl] ASC, [CodUnitate] ASC),
    CONSTRAINT [FK_ArticoleAliniate_ArticoleAliniate] FOREIGN KEY ([AAParinte], [CodUnitate]) REFERENCES [dbo].[ArticoleAliniate] ([ArtAl], [CodUnitate]),
    CONSTRAINT [FK_ArticoleAliniate_Unitati] FOREIGN KEY ([CodUnitate]) REFERENCES [dbo].[Unitati] ([CodUnitate])
);


GO
CREATE TRIGGER [dbo].[ActTerminal]
ON [dbo].[ArticoleAliniate]
FOR INSERT,UPDATE,DELETE 
AS 
BEGIN
IF UPDATE(AAParinte)
BEGIN
	UPDATE [ArticoleAliniate] SET Terminal=0 FROM inserted i WHERE [ArticoleAliniate].[ArtAl] = i.[AAParinte]
    
END
    IF (SELECT COUNT(*) FROM [ArticoleAliniate] a JOIN Deleted d  ON a.[AAParinte] = d.[AAParinte])=0
		UPDATE [ArticoleAliniate] SET Terminal = 1 FROM deleted d WHERE [ArticoleAliniate].[ArtAl] = d.[AAParinte]

END